<!--
/**
 *
 图片（image）: 10M，支持PNG\JPEG\JPG\GIF格式
 语音（voice）：2M，播放长度不超过60s，支持AMR\MP3格式
 视频（video）：10MB，支持MP4格式
 缩略图（thumb）：64KB，支持JPG格式
 */
 -->

<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="消息标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入消息标题"
          clearable
          @keyup.enter.native="title"
        />
      </el-form-item>

      <el-form-item label="消息类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="消息类型" clearable>
          <el-option
            v-for="dict in sys_new_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>

      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />

      <el-table-column
        label="消息标题"
        align="center"
        prop="title"
        min-width="300"
        show-overflow-tooltip
      />
      <el-table-column label="消息类型" align="center" prop="type" width="160">
        <template slot-scope="scope">
          <dict-tag :options="sys_new_type" :value="scope.row.type" />
        </template>
      </el-table-column>

      <el-table-column
        label="消息内容"
        prop="shortContext"
        min-width="200"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="图片预览"
        prop="context"
        width="120"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-if="scope.row.type === 'image'">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.description"
              :preview-src-list="imgUrlList"
            />
          </span>
          <span v-if="scope.row.type === 'video'">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.coverImage"
              :preview-src-list="imgUrlList"
            />
          </span>
        </template>
      </el-table-column>

      <el-table-column label="发布人" align="center" width="120">
        <template slot-scope="scope"> 系统管理员 </template>
      </el-table-column>
      <el-table-column
        label="发布时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleNews(scope.row)"
            >消息预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10]"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="消息标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入消息标题"
                :disabled="businessType === 'view'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="消息类型" prop="type">
              <el-radio-group v-model="form.type" @change="handleType">
                <el-radio
                  v-for="dict in sys_new_type"
                  :key="dict.value"
                  :label="dict.value"
                  :disabled="businessType === 'view'"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 图片消息 -->
            <el-form-item
              v-if="form.type === 'image'"
              label="上传图片"
              prop="description"
            >
              <div class="file-upload">
                <el-upload
                  ref="fileUpload0"
                  :action="action"
                  :headers="headers"
                  name="file"
                  :data="{ type: 'image' }"
                  :before-upload="beforeAvatarUploadImage"
                  :limit="1"
                  :on-error="handleUploadError"
                  :on-exceed="exceedHandler"
                  :on-success="
                    (res) => {
                      handleUploadSuccess(res, 'image')
                    }
                  "
                  :on-remove="
                    (file) => {
                      handleRemove(file, 'image')
                    }
                  "
                  :file-list="fileListImage"
                  class="upload-file-uploader"
                  list-type="picture-card"
                  :on-preview="
                    (file) => {
                      handlePreview(file, 'image')
                    }
                  "
                  :disabled="businessType === 'view'"
                >
                  <i class="el-icon-plus" />
                  <!-- 上传提示 -->
                  <div class="el-upload__tip" slot="tip">
                    请上传
                    <template>
                      格式为<b style="color: #f56c6c">{{
                        imageTypeList.join('/')
                      }}</b
                      >的 大小不超过
                      <b style="color: #f56c6c">{{ fileSizeImage }}MB</b>的<b
                        style="color: #f56c6c"
                        >1</b
                      >个图片
                    </template>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 图片消息 -->
            <el-form-item
              v-if="form.type === 'video'"
              label="视频缩略图"
              prop="coverImage"
            >
              <div class="file-upload">
                <el-upload
                  ref="fileUpload0"
                  :action="action"
                  :headers="headers"
                  name="file"
                  :data="{ type: 'image' }"
                  :before-upload="beforeAvatarUploadImage"
                  :limit="1"
                  :on-error="handleUploadError"
                  :on-exceed="exceedHandler"
                  :on-success="
                    (res) => {
                      handleUploadSuccess(res, 'coverImage')
                    }
                  "
                  :on-remove="
                    (file) => {
                      handleRemove(file, 'coverImage')
                    }
                  "
                  :file-list="fileListImage"
                  class="upload-file-uploader"
                  list-type="picture-card"
                  :on-preview="
                    (file) => {
                      handlePreview(file, 'image')
                    }
                  "
                  :disabled="businessType === 'view'"
                >
                  <i class="el-icon-plus" />
                  <!-- 上传提示 -->
                  <div class="el-upload__tip" slot="tip">
                    请上传
                    <template>
                      格式为<b style="color: #f56c6c">{{
                        imageTypeList.join('/')
                      }}</b
                      >的 大小不超过
                      <b style="color: #f56c6c">{{ fileSizeImage }}MB</b>的<b
                        style="color: #f56c6c"
                        >1</b
                      >个图片
                    </template>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 视频消息 -->
            <el-form-item
              v-if="form.type === 'video'"
              label="上传视频"
              prop="description"
            >
              <div class="file-upload">
                <el-upload
                  ref="fileUpload1"
                  :action="action"
                  :headers="headers"
                  name="file"
                  :data="{ type: 'video' }"
                  :before-upload="beforeAvatarUploadVideo"
                  :limit="1"
                  :on-error="handleUploadError"
                  :on-exceed="exceedHandler"
                  :on-success="
                    (file) => {
                      handleUploadSuccess(file, 'video')
                    }
                  "
                  :on-remove="
                    (file) => {
                      handleRemove(file, 'video')
                    }
                  "
                  :file-list="fileListVideo"
                  class="upload-file-uploader"
                  :on-preview="
                    (file) => {
                      handlePreview(file, 'video')
                    }
                  "
                  :disabled="businessType === 'view'"
                >
                  <!-- 上传按钮 -->
                  <el-button
                    type="primary"
                    icon="el-icon-upload"
                    plain
                    size="mini"
                    >视频上传</el-button
                  >
                  <!-- 上传提示 -->
                  <div class="el-upload__tip" slot="tip">
                    请上传
                    <template>
                      格式为<b style="color: #f56c6c">{{
                        videoTypeList.toString()
                      }}</b
                      >的 大小不超过
                      <b style="color: #f56c6c">{{ fileSizeVideo }}MB</b>的<b
                        style="color: #f56c6c"
                        >1</b
                      >个文件
                    </template>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 文本消息 -->
            <el-form-item label="消息内容" prop="context">
              <el-input
                v-model="form.context"
                type="textarea"
                :autosize="{ minRows: 10, maxRows: 15 }"
                placeholder="请输入消息内容"
                maxlength="1000"
                show-word-limit
                :disabled="businessType === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="businessType !== 'view'"
          type="primary"
          @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="openView"
      width="60%"
      append-to-body
    >
      <el-descriptions class="margin-top" title="" :column="1" border>
        <el-descriptions-item
          label-class-name="my-label"
          content-class-name="my-content"
        >
          <template slot="label"> 消息标题 </template>
          {{ form.title }}
        </el-descriptions-item>

        <el-descriptions-item
          label-class-name="my-label"
          content-class-name="my-content"
        >
          <template slot="label"> 消息类型 </template>
          <dict-tag :options="sys_new_type" :value="form.type" />
        </el-descriptions-item>

        <!-- 图片地址 -->
        <el-descriptions-item
          v-if="form.type === 'image'"
          label-class-name="my-label"
          content-class-name="my-content"
        >
          <template slot="label"> 图片预览 </template>
          <el-image
            v-if="form.description !== '' && form.description != null"
            style="width: 50px; height: 50px"
            :src="form.description"
            :preview-src-list="[form.description]"
          />
        </el-descriptions-item>

        <!-- 图片地址 -->
        <el-descriptions-item
          v-if="form.type === 'video'"
          label-class-name="my-label"
          content-class-name="my-content"
        >
          <template slot="label"> 缩略图预览 </template>
          <el-image
            v-if="form.coverImage !== '' && form.coverImage != null"
            style="width: 50px; height: 50px"
            :src="form.coverImage"
            :preview-src-list="[form.coverImage]"
          />
        </el-descriptions-item>
        <!-- 视频预览 -->
        <el-descriptions-item
          v-if="form.type === 'video'"
          label-class-name="my-label"
          content-class-name="my-content"
        >
          <template slot="label"> 视频预览 </template>

          <el-button
            type="success"
            icon="el-icon-view"
            plain
            @click.stop="handlePreview({ url: form.description }, 'video')"
            >视频预览</el-button
          >
        </el-descriptions-item>
        <el-descriptions-item
          label-class-name="my-label"
          content-class-name="my-content"
        >
          <template slot="label"> 消息内容 </template>
          {{ form.context }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  getNewsList,
  addNews,
  getByMaterialId,
  deleteNews
} from '@/api/newManage.js'
import { getToken } from '@/utils/auth'
export default {
  name: 'news',

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      businessType: 'add',
      // 表格数据
      list: [],
      sys_new_type: [
        {
          label: '文本消息',
          value: 'text',
          raw: {
            listClass: 'primary'
          }
        },
        {
          label: '图片消息',
          value: 'image',
          raw: {
            listClass: 'success'
          }
        },
        {
          label: '视频消息',
          value: 'video',
          raw: {
            listClass: 'warning'
          }
        }
      ],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        type: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {
            required: true,
            message: '消息标题不能为空',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择消息类型',
            trigger: 'change'
          }
        ],
        context: [
          {
            required: true,
            message: '消息内容不能为空',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请上传文件',
            trigger: 'change'
          }
        ],
        coverImage: [
          {
            required: true,
            message: '请上传视频缩略图',
            trigger: 'change'
          }
        ]
      },

      // headers
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 上传地址
      // action: process.env.VUE_APP_BASE_API + '/common/upload',
      action: process.env.VUE_APP_BASE_API + '/wechat/materialLib/upload',
      backUrl: 'http://wxai.cmqps.xyz:8090',

      imgUrlList: [],

      // PNG\JPEG\JPG\GIF
      imageTypeList: ['png', 'jpeg', 'jpg', 'gif'],
      fileSizeImage: '50',
      fileListImage: [],
      videoTypeList: ['mp4'],
      fileSizeVideo: '50',
      fileListCoverImage: [],

      fileListVideo: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询列表 */

    async getList() {
      this.loading = true
      this.imgUrlList = []

      const res = await getNewsList(this.queryParams)
      this.list = res.data.records || []
      this.total = res.data.total

      this.loading = false

      this.list.forEach((item) => {
        item.shortContext = this.shortContext(item)
        if (item.type === 'image' || item.type === 'video') {
          // 图片 视频
          if (item.type === 'image') {
            const mediaUrl = item.description || ''
            if (mediaUrl !== '') {
              item.description = this.backUrl + mediaUrl
              this.imgUrlList.push(item.description)
            }
          } else {
            const mediaUrl2 = item.description || ''
            if (mediaUrl2 !== '') {
              item.description = this.backUrl + mediaUrl2
            }

            const coverImage = item.coverImage || ''
            if (coverImage !== '') {
              item.coverImage = this.backUrl + coverImage
              this.imgUrlList.push(item.coverImage)
            }
          }
        }
      })
    },

    // 短标题截取
    shortContext(row) {
      const str = row.context || ''
      if (str && str.length > 50) {
        // 从头向后截取 50 个字符
        return str.substring(0, 50) + '...'
      } else {
        // 直接返回原字符串
        return str
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.openView = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        type: 'text',
        description: undefined,
        context: undefined,
        coverImage: undefined
      }

      this.fileListImage = []
      this.fileListVideo = []
      this.fileListCoverImage = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.businessType = 'add'
      this.reset()
      this.open = true
      this.title = '添加消息'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /* 详情按钮操作 */
    handleNews(row) {
      console.log('ROW', row)
      this.businessType = 'view'
      this.reset()
      this.form = Object.assign({}, row)

      const fileUrl = row.context || ''
      const fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1)
      if (row.type === 'image') {
        this.fileListImage = [
          {
            name: fileName,
            url: fileUrl
          }
        ]
        this.fileListVideo = []
      } else if (row.type === 'video') {
        this.fileListVideo = [
          {
            name: fileName,
            url: fileUrl
          }
        ]
        this.fileListImage = []
      }
      this.openView = true
      this.title = '消息预览'
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.form)

          addNews(params).then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return deleteNews(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 消息类型选择操作 */
    handleType(e) {
      console.log('消息类型选择操作', e)
    },

    // 文件上传前操作
    beforeAvatarUploadImage(file) {
      console.log('file', file)

      // return new Promise((resolve, reject) => {
      // 判断上传格式*****************
      let fileName = file.name
      fileName = fileName.substring(fileName.lastIndexOf('.') + 1)
      const fileTypeList = this.imageTypeList
      const isTypeOk = fileTypeList.indexOf(fileName) >= 0

      const fileSize = this.fileSizeImage
      const isLt100M = file.size / 1024 / 1024 < fileSize

      if (!isTypeOk) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${fileTypeList.join('/')}格式文件!`
        )
        return false
      } else if (!isLt100M) {
        this.$message.error('上传文件大小不能超过' + fileSize + 'MB!')
        return false
      } else {
        this.$modal.loading('正在上传文件，请稍候...')
        return isTypeOk && isLt100M
      }
    },
    beforeAvatarUploadVideo(file) {
      console.log('file', file)

      // return new Promise((resolve, reject) => {
      // 判断上传格式*****************
      let fileName = file.name
      fileName = fileName.substring(fileName.lastIndexOf('.') + 1)
      const fileTypeList = this.videoTypeList
      const isTypeOk = fileTypeList.indexOf(fileName) >= 0

      const fileSize = this.fileSizeVideo
      const isLt100M = file.size / 1024 / 1024 < fileSize

      if (!isTypeOk) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${fileTypeList.join('/')}格式文件!`
        )
        return false
      } else if (!isLt100M) {
        this.$message.error('上传文件大小不能超过' + fileSize + 'MB!')
        return false
      } else {
        this.$modal.loading('正在上传文件，请稍候...')
        return isTypeOk && isLt100M
      }
    },

    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError('上传失败，请重试')
      this.$modal.closeLoading()
    },

    // 文件超出个数限制
    exceedHandler(files) {
      this.$message.error('只能上传1个文件')
    },
    // 上传成功之后的操作
    handleUploadSuccess(res, type) {
      /**
       *
       *
       * {"msg":"操作成功",
       * "fileName":"/profile/upload/2025/04/20/0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004_20250420200055A001.mp4",
       * "code":200,
       * "newFileName":"0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004_20250420200055A001.mp4",
       * "url":"http://localhost:8088/profile/upload/2025/04/20/0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004_20250420200055A001.mp4",
       * "originalFilename":"0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004.mp4"}
       *
       *
       */
      console.log('res', res)
      this.$modal.closeLoading()
      if (res.code !== 200) {
        this.$modal.msgError(res.msg)
        return
      }

      // const fileUrl = res.url
      // const fileName = res.newFileName

      const fileUrl = res.data.profile
      const fileName = res.data.fileName
      const mediaId = res.data.mediaId || ''

      this.form.mediaId = mediaId
      if (type === 'image') {
        this.form.description = fileUrl
        this.fileListImage = [
          {
            name: fileName,
            url: this.backUrl + fileUrl
          }
        ]
      } else if (type === 'coverImage') {
        this.form.coverImage = fileUrl
        this.fileListCoverImage = [
          {
            name: fileName,
            url: this.backUrl + fileUrl
          }
        ]
      } else {
        this.form.description = fileUrl
        this.fileListVideo = [
          {
            name: fileName,
            url: this.backUrl + fileUrl
          }
        ]
      }
    },
    //    删除文件
    handleRemove(e, type) {
      if (type === 'image') {
        this.form.description = ''
        this.fileListImage = []
      } else if (type === 'coverImage') {
        this.form.coverImage = ''
        this.fileListCoverImage = []
      } else {
        this.form.description = ''
        this.fileListVideo = []
      }
    },
    // 图片预览
    handlePreview(file, type) {
      if (type === 'image') {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      } else {
        window.open(file.url)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.my-label {
  width: 100px;
}
</style>
